<template>
  <el-dialog draggable v-model="dialog.show" width="800px" top="50px" :before-close="handleClose" class="custom-dialog">
    <template #header> 编辑角色 </template>
    <div class="custom-dialog-box">
      <el-form :model="forms" ref="registerRef" :rules="rules" label-width="100">
        <el-form-item label="名称:" prop="roleName">
          <el-input v-model="forms.roleName" placeholder="请输入名称" clearable class="width-220"></el-input>
        </el-form-item>
        <el-form-item label="操作权限:" prop="permissionIds">
          <div class="dis-flex flex-dir-column">
            <el-button type="success" plain @click="expandHandle">一键{{ dialog.treeType ? '展开' : '收起' }}</el-button>
            <el-tree
              ref="treeRef"
              :data="role"
              show-checkbox
              node-key="id"
              check-on-click-node
              default-expand-all
              :expand-on-click-node="false"
              :props="{ class: customNodeClass }"
            />
          </div>
        </el-form-item>
        <el-form-item label="数据权限:">
          <el-radio-group v-model="forms.showDataType">
            <el-radio :label="1">
              <el-tooltip placement="top" effect="dark">
                <template #content>
                  <p>只能查看自己以及下属参与的订单</p>
                  <p>成员只要作为负责人、销售、创建人 或任务负责人中的任意一个，即参与了该订单</p>
                  <p>只能查看自己以及下属负责的或公司共享的客户</p>
                </template>
                个人
              </el-tooltip>
            </el-radio>
            <el-radio :label="2">
              <el-tooltip placement="top" effect="dark">
                <template #content>
                  <p>能查看自己以及下属、同部门成员参与的订单</p>
                  <p>能查看自己以及下属、同部门成员负责的或公司共享的客户</p>
                </template>
                下属部门
              </el-tooltip>
            </el-radio>
            <el-radio :label="3">
              <el-tooltip placement="top" effect="dark">
                <template #content>
                  <p>能查看全公司所有的订单、客户</p>
                </template>
                全公司
              </el-tooltip>
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <z-button icon="close" type="default" @click="handleClose">取消</z-button>
        <z-button icon="check" @click="onCheck"> 确认 </z-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { post } from '@/api/index.js';
import { role } from '@/config/data.js';
const $message = inject('$message');
let emit = defineEmits(['update:modelValue', 'onSave']);
let props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  editData: {
    type: Object,
    default: () => {
      return {};
    }
  }
});
let treeRef = ref();
let registerRef = ref();
let dialog = reactive({
  show: false,
  treeType: false
});
let formsInit = () => {
  return reactive({
    id: 0,
    roleName: '',
    showDataType: 1,
    isAdmin: false,
    permissionIds: []
  });
};
let forms = formsInit();
const validateRole = (rule, value, callback) => {
  if (!treeRef.value.getCheckedKeys(false).length) {
    callback(new Error('未勾选页面权限!'));
  }
  callback();
};
let rules = {
  roleName: [{ required: true, trigger: 'blur', message: '名称不能为空!' }],
  permissionIds: [{ required: true, validator: validateRole, trigger: 'blur' }]
};

watch(
  () => props.modelValue,
  val => {
    dialog.show = val;
    if (!val) return;
    const formData = formsInit();
    Object.keys(formData).map(r => {
      forms[r] = props.editData[r] != undefined ? props.editData[r] : formData[r];
    });
    nextTick(() => {
      let arr = [...forms.permissionIds];
      role.map(r => {
        if (!r.children) return;
        if (!arr.includes(r.id)) return;
        // 匹配是否有子节点 不在页面权限中的。 就是区分，本来是全选中的，但是因为调整了页面权限，导致tree因为父节点选中，导致子节点全部选中了。
        const type = r.children.some(row => !arr.includes(row.id));
        if (!type) return;
        // 如果type 为true。就代表了，父节点选中，但是实际 子节点不应该选中。
        forms.permissionIds.splice(
          forms.permissionIds.findIndex(row => row === r.id),
          1
        );
      });
      treeRef.value.setCheckedKeys(forms.permissionIds);
    });
  },
  { immediate: true }
);
const handleClose = () => {
  emit('update:modelValue', false);
};
const onCheck = () => {
  registerRef.value.validate(async val => {
    if (!val) return;
    let params = { ...forms };
    params.permissionIds = treeRef.value.getCheckedKeys(false);
    await post('Role/AddOrUpdate', params);
    $message.success('保存成功');
    emit('onSave');
  });
};
const customNodeClass = data => {
  return data.isPenultimate ? 'is-penultimate' : null;
};
/**
 * 展开折叠tree
 **/
const expandHandle = () => {
  let nodes = treeRef.value.store.nodesMap;
  for (const node in nodes) {
    nodes[node].expanded = dialog.treeType;
  }
  dialog.treeType = !dialog.treeType;
};
</script>

<style lang="scss">
.is-penultimate {
  .el-tree-node__children {
    padding-left: 60px;
    white-space: pre-wrap;
    line-height: 12px;
    .el-tree-node {
      display: inline-block;
    }
    .el-tree-node__content {
      padding-left: 10px !important;
      padding-right: 5px !important;
      .el-tree-node__expand-icon {
        display: none;
      }
    }
  }
}
</style>
